class Snake {
    head:HTMLElement // 蛇头
    bodies:HTMLCollection // 蛇身体
    elemet:HTMLElement
    constructor(){
        this.elemet = document.querySelector('#snake') as HTMLElement
        this.head = document.querySelector('#snake > div') as HTMLElement
        this.bodies = this.elemet!.getElementsByTagName('div')
    }

    get X (){
        return this.head.offsetLeft
    }
    get Y (){
        return this.head.offsetTop
    }

    set X(value:number){
        // 设置蛇之前需要保证当前的value值不跟原来的一样
        if(this.X == value) return
        if(value < 0 || value > 290) {
            throw Error('蛇撞到墙体了')
        }
        if(this.bodies[1] && (<HTMLElement>this.bodies[1]).offsetLeft == value) {
            if(value > this.X){
                value = this.X - 10
            }else {
                value = this.X + 10
            }
        }
        this.bodyMove()
        this.head.style.left = value + 'px'
        
        
    }
    set Y(value:number){
        if(this.Y == value) return
        if(value < 0 || value > 290) {
            throw Error('蛇撞到墙体了')
        }
        if(this.bodies[1] && (<HTMLElement>this.bodies[1]).offsetTop == value) {
            if(value > this.X){
                value = this.Y - 10
            }else {
                value = this.Y + 10
            }
            
        }
        this.bodyMove()
        this.head.style.top = value + 'px'
        
    }

    // 添加蛇的身体
    addBody(){
        this.elemet.insertAdjacentHTML('beforeend','<div></div>')
    }
    // 身体的移动
    bodyMove(){
        for(let bodyIndex = this.bodies.length - 1;bodyIndex > 0; bodyIndex--){
            let x = (this.bodies[bodyIndex - 1] as HTMLElement).offsetLeft
            let y = (<HTMLElement>this.bodies[bodyIndex - 1]).offsetTop;
            
            (<HTMLElement>this.bodies[bodyIndex]).style.left = x + 'px';
            (<HTMLElement>this.bodies[bodyIndex]).style.top = y + 'px'
        }
    }
}

export default Snake